package com.shajj.data.record;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.DatastoreNeedIndexException;
import com.google.appengine.api.datastore.DatastoreTimeoutException;
import com.shajj.data.Record;
import com.shajj.data.SearchJanitorUtils;

public class RecordSearchJanitor {

	private static final Logger log = Logger.getLogger(RecordSearchJanitor.class.getName());

	public static final int MAXIMUM_NUMBER_OF_WORDS_TO_SEARCH = 5;

	public static final int MAX_NUMBER_OF_WORDS_TO_PUT_IN_INDEX = 200;

	@SuppressWarnings("unchecked")
	public static List<Record> search(String queryString, PersistenceManager pm) {
		StringBuffer queryBuffer = new StringBuffer();
		queryBuffer.append("SELECT FROM " + Record.class.getName() + " WHERE ");
		Set<String> queryTokens = SearchJanitorUtils.getTokensForIndexingOrQuery(queryString, MAXIMUM_NUMBER_OF_WORDS_TO_SEARCH);
		List<String> parametersForSearch = new ArrayList<String>(queryTokens);
		StringBuffer declareParametersBuffer = new StringBuffer();
		int parameterCounter = 0;
		while (parameterCounter < queryTokens.size()) {
			queryBuffer.append("fts == param" + parameterCounter);
			declareParametersBuffer.append("String param" + parameterCounter);
			if (parameterCounter + 1 < queryTokens.size()) {
				queryBuffer.append(" && ");
				declareParametersBuffer.append(", ");
			}
			parameterCounter++;
		}

		Query query = pm.newQuery(queryBuffer.toString());
		query.declareParameters(declareParametersBuffer.toString());
		List<Record> result = null;
		try {
			result = (List<Record>) query.executeWithArray(parametersForSearch.toArray());
		} catch (DatastoreTimeoutException e) {
			log.severe(e.getMessage());
			log.severe("datastore timeout at: " + queryString);
		} catch (DatastoreNeedIndexException e) {
			log.severe(e.getMessage());
			log.severe("datastore need index exception at: " + queryString);
		}
		return result;
	}

	public static void updateFTSStuffForThread(Record thread) {
		StringBuffer sb = new StringBuffer();
		sb.append(thread.getContent());
		Set<String> new_ftsTokens = SearchJanitorUtils.getTokensForIndexingOrQuery(sb.toString(), MAX_NUMBER_OF_WORDS_TO_PUT_IN_INDEX);
		Set<String> ftsTokens = thread.getFts();
		ftsTokens.clear();
		for (String token : new_ftsTokens) {
			ftsTokens.add(token);
		}
	}

}
